package com.hotelvip.common.jwt;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hotelvip.common.pojo.JWTToken;
import com.hotelvip.common.utils.JSONResult;
import com.hotelvip.common.utils.JwtUtil;
import com.hotelvip.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Lzh
 * @date 2020/12/8 8:59
 */
@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {


    /**
     * 判断是否允许通过
     *
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("isAccessAllowed方法");
        try{
            return executeLogin(request, response);
        }catch (Exception e){
            log.info("错误"+e);
            responseError(response,"shiro fail");
            return false;
        }
    }
    /**
     * 是否进行登录请求
     *
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        log.info("isLoginAttempt方法");
        String token=((HttpServletRequest)request).getHeader("Authorization");
        return token != null;
    }

    /**
     * 创建shiro token
     *
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        log.info("createToken方法");
        String jwtToken = ((HttpServletRequest)request).getHeader("Authorization");

        if(jwtToken!=null) {
            return new JWTToken(jwtToken);
        }
        return null;
    }
    /**
     * isAccessAllowed为false时调用，验证失败
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        log.info("onAccessDenied");

        this.sendChallenge(request,response);
        responseError(response,"Token 过期或存在问题");
        return false;
    }


    /**
     * shiro验证成功调用
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) {
        log.info("onLoginSuccess：");
        RedisUtils redisUtils = new RedisUtils();
        String jwttoken= (String) token.getPrincipal();
        if (jwttoken!=null){
            try{
                if(JwtUtil.verify(jwttoken)){
                    //判断Redis是否存在所对应的RefreshToken
                    long userId = JwtUtil.getUserId(jwttoken);
                    Long currentTime=JwtUtil.getCurrentTime(jwttoken);
                    if (redisUtils.exist("SYS_USER::["+userId+"]")) {
                        Long currentTimeMillisRedis = Long.valueOf(redisUtils.get("SYS_USER::["+userId+"]"));
                        return currentTimeMillisRedis.equals(currentTime);
                    }
                }
                return false;
            }catch (Exception e){
                log.info("token验证："+e.getClass());
                if (e instanceof TokenExpiredException){
                    log.info("Token 存在问题");
                    return refreshToken(request, response);
                }
            }
        }
        return true;
    }

    /**
     * 刷新AccessToken，进行判断RefreshToken是否过期，未过期就返回新的AccessToken且继续正常访问
     */
    private boolean refreshToken(ServletRequest request, ServletResponse response) {

        RedisUtils redisUtils = new RedisUtils();
        String token = ((HttpServletRequest)request).getHeader("Authorization");
        long userId = JwtUtil.getUserId(token);
        Long currentTime=JwtUtil.getCurrentTime(token);
        // 判断Redis中RefreshToken是否存在
        if (redisUtils.exist("sysUserHotel"+userId)) {
            // Redis中RefreshToken还存在，获取RefreshToken的时间戳
            Long currentTimeMillisRedis = Long.valueOf(redisUtils.get("sysUserHotel"+userId));
            // 获取当前AccessToken中的时间戳，与RefreshToken的时间戳对比，如果当前时间戳一致，进行AccessToken刷新
            if (currentTimeMillisRedis.equals(currentTime)) {
                // 获取当前最新时间戳
                Long currentTimeMillis =System.currentTimeMillis();
                redisUtils.setex("sysUserHotel"+userId,(int) JwtUtil.REFRESH_EXPIRE_TIME, Long.toString(currentTimeMillis));
                // 刷新AccessToken，设置时间戳为当前最新时间戳
                token = JwtUtil.sign(userId, currentTimeMillis);
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                httpServletResponse.setHeader("Authorization", token);
                httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
                return true;
            }
        }
        return false;
    }

    /**
     * 拦截器的前置方法，此处进行跨域处理
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest= (HttpServletRequest) request;
        HttpServletResponse httpServletResponse= (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin",httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers",httpServletRequest.getHeader("Access-Control-Resquest-Headers"));
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())){
            httpServletResponse.setStatus(HttpStatus.OK.value());
        }

        //如果不带token，不去验证shiro
        if (!isLoginAttempt(request,response)){
            responseError(httpServletResponse,"no token");
            return false;
        }
        return super.preHandle(request,response);
    }




    private void responseError(ServletResponse response, String msg){
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(200);
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=UTF-8");
        try {
            String rj = new ObjectMapper().writeValueAsString(new JSONResult(401, msg, null));
            httpResponse.getWriter().append(rj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
